package com.example.smartlearning.tool.XingHuo.QucikMath;//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
@Component
public class WebITR {
    private static final String WebITR_URL = "https://rest-api.xfyun.cn/v2/itr";
    private static final String APPID = "036f2ff8";
    private static final String API_KEY = "3ae6c249538e8e6a857794be250a5791";
    private static final String API_SECRET = "NjFiZWQ1ZTM0MDU3MGY0ZGY2NDExOWU4";
    private static final String AUDIO_PATH = "/www/wwwroot/SmartLearning/pic/math.jpg";

    public WebITR() {
    }

    public String ITR() throws Exception {
        String body = buildHttpBody();
        Map<String, String> header = buildHttpHeader(body);
        Map<String, Object> resultMap = HttpUtil.doPost2("https://rest-api.xfyun.cn/v2/itr", header, body);
        if (resultMap != null) {
            String resultStr = resultMap.get("body").toString();
            System.out.println("【ITR WebAPI 接口调用结果】\n" + resultStr);
            File file = new File("/www/wwwroot/SmartLearning/pic/math.jpg");
            file.delete();
            Gson json = new Gson();
            ResponseData resultData = json.fromJson(resultStr, ResponseData.class);
            int code = resultData.getCode();
            if (resultData.getCode() != 0) {
                System.out.println("请前往https://www.xfyun.cn/document/error-code?code=" + code + "查询解决办法");
            }
            return resultStr;
        } else {
            return "调用失败！请根据错误信息检查代码，接口文档：https://www.xfyun.cn/doc/words/photo-calculate-recg/API.html";
        }

    }

    public static Map<String, String> buildHttpHeader(String body) throws Exception {
        Map<String, String> header = new HashMap();
        URL url = new URL("https://rest-api.xfyun.cn/v2/itr");
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date dateD = new Date();
        String date = format.format(dateD);
        String digestBase64 = "SHA-256=" + signBody(body);
        StringBuilder builder = (new StringBuilder("host: ")).append(url.getHost()).append("\n").append("date: ").append(date).append("\n").append("POST ").append(url.getPath()).append(" HTTP/1.1").append("\n").append("digest: ").append(digestBase64);
        String sha = hmacsign(builder.toString(), "NjFiZWQ1ZTM0MDU3MGY0ZGY2NDExOWU4");
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", "3ae6c249538e8e6a857794be250a5791", "hmac-sha256", "host date request-line digest", sha);
        header.put("Authorization", authorization);
        header.put("Content-Type", "application/json");
        header.put("Accept", "application/json,version=1.0");
        header.put("Host", url.getHost());
        header.put("Date", date);
        header.put("Digest", digestBase64);
        return header;
    }

    public static String buildHttpBody() throws Exception {
        JsonObject body = new JsonObject();
        JsonObject business = new JsonObject();
        JsonObject common = new JsonObject();
        JsonObject data = new JsonObject();
        common.addProperty("app_id", "036f2ff8");
        business.addProperty("ent", "math-arith");
        business.addProperty("aue", "raw");
        byte[] imageByteArray = FileUtil.read("/www/wwwroot/SmartLearning/pic/math.jpg");
        String imageBase64 = new String(Base64.getEncoder().encodeToString(imageByteArray));
        data.addProperty("image", imageBase64);
        body.add("common", common);
        body.add("business", business);
        body.add("data", data);
        return body.toString();
    }

    private static String signBody(String body) throws Exception {
        String encodestr = "";

        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(body.getBytes("UTF-8"));
            encodestr = Base64.getEncoder().encodeToString(messageDigest.digest());
        } catch (NoSuchAlgorithmException var4) {
            var4.printStackTrace();
        } catch (UnsupportedEncodingException var5) {
            var5.printStackTrace();
        }

        return encodestr;
    }

    private static String hmacsign(String signature, String apiSecret) throws Exception {
        Charset charset = Charset.forName("UTF-8");
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(charset), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(signature.getBytes(charset));
        return Base64.getEncoder().encodeToString(hexDigits);
    }

    public static class ResponseData {
        private int code;
        private String message;
        private String sid;
        private Object data;

        public ResponseData() {
        }

        public int getCode() {
            return this.code;
        }

        public String getMessage() {
            return this.message;
        }

        public String getSid() {
            return this.sid;
        }

        public Object getData() {
            return this.data;
        }
    }
}
